from itsdangerous import TimedJSONWebSignatureSerializer as TimeSerializer
from itsdangerous import TimedJSONWebSignatureSerializer as Serializer, BadData
from django.conf import settings


# 生成邮箱验证链接
def generate_verify_email_url(user):
    """
    :param user: 当前用户
    :return: verify_url
    """
    serializer = TimeSerializer(settings.SECRET_KEY, expires_in=3600)
    # 组装加密数据
    data = {'user_id': user.id, 'email': user.email}
    # data加密转字符串
    token = serializer.dumps(data).decode()
    # 链接地址拼接加密数据
    verify_url = settings.EMAIL_VERIFY_URL + '?token=' + token

    return verify_url


# 验证token并提取user
def check_verify_email_token(token):
    """
    :param token: 用户信息签名
    :return: user, None
    """
    serializer = Serializer(settings.SECRET_KEY, expires_in=600)
    try:
        data = serializer.loads(token)
    except BadData:
        print('获取用户数据失败, 激活邮件过期')
        return None
    else:
        user_id = data.get('user_id')
        return user_id
